package com.retirement.policy.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.retirement.policy.domain.dto.PropertyPolicyAddDto;
import com.retirement.policy.domain.dto.PropertyPolicyDto;
import com.retirement.policy.domain.dto.PropertyPolicyUpdateDto;
import com.retirement.policy.mapper.PropertyPolicyMapper;
import com.retirement.policy.service.IPropertyPolicyService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.retirement.policy.entity.PropertyPolicy;
import org.springframework.util.Assert;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lijy
 * @since 2024-01-16
 */
@Service
public class PropertyPolicyServiceImpl extends ServiceImpl<PropertyPolicyMapper, PropertyPolicy> implements IPropertyPolicyService {

    /**
     * @Title: 初始爬取数据
     */
    @Override
    public void fetchAndStorePolicy() {
        // 爬取小程序全国政策的接口
        loopAndStoreOpen();

        // 爬取小程序广东政策的接口
        loopAndStore();

        // 爬取园区无忧接口数据
        loopAndStorePolicy();
    }

    /**
     * @Title: 更新数据
     */
    @Override
    public void updatePolicy() {
        updateYqPolicy();
    }

    @Override
    public List<PropertyPolicy> getListPolicy(PropertyPolicyDto dto) {
        List<PropertyPolicy> list = baseMapper.getListPolicy(dto);
        return list;
    }

    @Override
    public int updatePolicy(PropertyPolicyUpdateDto dto) {
        Assert.isTrue(ObjectUtil.isNotNull(dto.getId()), "无id信息");
        PropertyPolicy bean = baseMapper.selectById(dto.getId());
        Assert.isTrue(ObjectUtil.isNotNull(bean), "该信息不存在");
        BeanUtils.copyProperties(dto,bean);

        return baseMapper.updateById(bean);
    }

    @Override
    public int addPolicy(PropertyPolicyAddDto dto) {
        PropertyPolicy propertyPolicy = new PropertyPolicy();
        propertyPolicy.setId(IdUtil.simpleUUID());
        propertyPolicy.setPolicySource("自主添加");
        propertyPolicy.setPublishingStatus(1);
        propertyPolicy.setRevocationStatus(1);
        propertyPolicy.setPinnedStatus(0);
        BeanUtils.copyProperties(dto,propertyPolicy);

        return baseMapper.insert(propertyPolicy);
    }

    @Override
    public String relevantDocuments(PropertyPolicyDto dto) {

        return null;
    }

    public void updateYqPolicy(){
        try{
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(getYqPolicy(0,10));
            // 获取政策总数
            Integer totalPolicy = jsonNode.get("obj").get("totalSize").intValue();
            Integer totalCount = Math.toIntExact(baseMapper.selectCount(new LambdaQueryWrapper<PropertyPolicy>()
                    .eq(PropertyPolicy::getPolicySource, "园区无忧")) + baseMapper.selectPropertyPolicyFields());
            Integer totalPage;

            // 如果总数一样则不更新
            if(totalPolicy == totalCount){
                return;
            }else {
                if(totalCount > 0){
                    totalPage = Math.toIntExact(totalPolicy - totalCount) / 10;
                    // 循环更新，每次接口只返回十条数据
                    for(int pageNo = 0;pageNo <= totalPage;pageNo++){
                        String reponse = getYqPolicy(pageNo,10);
                        jsonNode = objectMapper.readTree(reponse);

                        if(jsonNode.get("error").get("err_code").intValue() != 0 ||
                                jsonNode.get("error").get("err_msg").equals("接口访问超出频率限制")){
//                            System.out.println("请求超时--------"+pageNo);
                            pageNo -= 1;
                            // 暂停20秒
                            try {
                                Thread.sleep(20000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }else{
                            storeYqPolicy(jsonNode,true);
                        }
                    }
                }
            }
        }catch (ExceptionInInitializerError e){
            e.getMessage();
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public void loopAndStorePolicy(){
        try{
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(getYqPolicy(0,10));
            // 获取数据总量，计算总页数
            Integer totalPage = jsonNode.get("obj").get("totalSize").intValue() / 10;
            for(int pageNo = 0;pageNo <= totalPage;pageNo++){
                String reponse = getYqPolicy(pageNo,10);
                jsonNode = objectMapper.readTree(reponse);

                if(jsonNode.get("error").get("err_code").intValue() != 0 ||
                        jsonNode.get("error").get("err_msg").equals("接口访问超出频率限制")){
//                    System.out.println("请求超时--------"+pageNo);
                    pageNo -= 1;
                    // 暂停20秒
                    try {
                        Thread.sleep(20000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    storeYqPolicy(jsonNode,false);
                }
            }
        }catch (Exception e){
            e.getMessage();
        }
    }

    public void loopAndStoreOpen(){
        try{
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(getYgPolicy(1,10));
            Integer totalPage = jsonNode.get("data").get("count").intValue() / 10;
            for(int pageNo = 1;pageNo <= totalPage+1;pageNo++){
                String reponse = getYgPolicy(pageNo,10);
                jsonNode = objectMapper.readTree(reponse);
                if(!ObjectUtil.isNotNull(jsonNode.get("data").get("result"))){
//                System.out.println("请求超时--------"+pageNo);
                    pageNo -= 1;
                    // 暂停20秒
                    try {
                        Thread.sleep(20000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    storeYgPolicy(jsonNode,true);
                }
            }
        }catch (Exception e){
            e.getMessage();
        }
    }

    public void loopAndStore(){
        try{
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(getGdPolicy(1,10));
            Integer totalPage = jsonNode.get("data").get("count").intValue() / 10;
            for(int pageNo = 1;pageNo <= totalPage+1;pageNo++){
                String reponse = getGdPolicy(pageNo,10);
                jsonNode = objectMapper.readTree(reponse);
                if(!ObjectUtil.isNotNull(jsonNode.get("data").get("result"))){
//                System.out.println("请求超时--------"+pageNo);
                    pageNo -= 1;
                    // 暂停20秒
                    try {
                        Thread.sleep(20000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    storeYgPolicy(jsonNode,false);
                }
            }
        }catch (Exception e){
            e.getMessage();
        }
    }

    public void storeYgPolicy(JsonNode jsonNode,boolean isOpen){
        try{
            JsonNode listNode = jsonNode.get("data").get("result");
            if(ObjectUtil.isNotNull(listNode)) {
                for (JsonNode itemNode : listNode) {
                    PropertyPolicy propertyPolicy = new PropertyPolicy();
                    propertyPolicy.setId(IdUtil.simpleUUID());
                    int flag = 0;
                    if (ObjectUtil.isNotNull(itemNode.get("id"))) {
                        propertyPolicy.setPolicyId(itemNode.get("id").asText());
                    }
//                    propertyPolicy = objectMapper.readValue(getPolicyDetail(propertyPolicy.getPolicyId()),PropertyPolicy.class);
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode policyDetail = objectMapper.readTree(getPolicyDetail(propertyPolicy.getPolicyId())).get("data");
//                    propertyPolicy = objectMapper.treeToValue(policyDetail,PropertyPolicy.class);
                    if(ObjectUtil.isNotNull(policyDetail)){
                        if(ObjectUtil.isNotNull(policyDetail.get("title"))){
                            propertyPolicy.setName(policyDetail.get("title").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("type"))){
                            propertyPolicy.setTypes(policyDetail.get("type").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("level"))){
                            propertyPolicy.setLevel(policyDetail.get("level").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("department"))){
                            propertyPolicy.setDepartment(policyDetail.get("department").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("create_time"))){
                            propertyPolicy.setWriteDate(policyDetail.get("create_time").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("dep_time"))){
                            propertyPolicy.setReleaseDate((policyDetail.get("dep_time").asText()));
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("username"))){
                            propertyPolicy.setWriteUserName(policyDetail.get("username").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("phone"))){
                            propertyPolicy.setPhone(policyDetail.get("phone").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("sort"))){
                            propertyPolicy.setSort(policyDetail.get("sort").asInt());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("province_id"))){
                            propertyPolicy.setProvince(policyDetail.get("province_id").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("city_id"))){
                            propertyPolicy.setCity(policyDetail.get("city_id").asText());
                        }
                        if(ObjectUtil.isNotNull((policyDetail.get("area_id")))){
                            propertyPolicy.setAreaId(policyDetail.get("area_id").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("view_number"))){
                            propertyPolicy.setViewNumber(policyDetail.get("view_number").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("visit_number"))){
                            propertyPolicy.setVisitNumber(policyDetail.get("visit_number").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("collection_number"))){
                            propertyPolicy.setCollectionNumber(policyDetail.get("collection_number").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("consult_number"))){
                            propertyPolicy.setConsultNumber(policyDetail.get("consult_number").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("images_name"))){
                            String images_name = policyDetail.get("images_name").asText();
                            if(images_name.length() > 255){
                                flag = 1;
                                propertyPolicy.setImagesName("此字段超长");
                            }else {
                                propertyPolicy.setImagesName(images_name);
                            }
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("images"))){
                            String images = policyDetail.get("images").asText();
                            if(images.length() > 65535){
                                flag = 1;
                                propertyPolicy.setImages("此字段超长");
                            }else {
                                propertyPolicy.setImages(images);
                            }
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("content"))){
                            propertyPolicy.setContent(policyDetail.get("content").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("type_name"))){
                            propertyPolicy.setTypesName(policyDetail.get("type_name").asText());
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("range"))){
                            String range = policyDetail.get("range").asText();
                            if(range.length() > 50){
                                flag = 1;
                                propertyPolicy.setRanged("此字段超长");
                            }else {
                                propertyPolicy.setRanged(policyDetail.get("range").asText());
                            }
                        }
                        if(ObjectUtil.isNotNull(policyDetail.get("is_collection"))){
                            propertyPolicy.setIsSubscribe(policyDetail.get("is_collection").asText());
                        }
                        if(isOpen){
                            propertyPolicy.setPolicyRange("全国");
                        }else{
                            propertyPolicy.setPolicyRange("广东省");
                        }
                        propertyPolicy.setPolicySource("医谷产孵");
                        propertyPolicy.setPublishingStatus(1);
                        propertyPolicy.setRevocationStatus(1);
                        propertyPolicy.setPinnedStatus(0);
                    }
                    if(flag == 1){
                        baseMapper.insertPropertyPolicyFields(propertyPolicy);
                    }else {
                        baseMapper.insert(propertyPolicy);
                    }
                }
            }
        }catch (Exception e){
            e.getMessage();
        }
    }

    public void storeYqPolicy(JsonNode jsonNode,boolean isUpdate){
        try{
            JsonNode listNode = jsonNode.get("obj").get("list");
            // 循环将数据存入数据库
            if(ObjectUtil.isNotNull(listNode)) {
                for (JsonNode itemNode : listNode) {
                    PropertyPolicy propertyPolicy = new PropertyPolicy();
                    // 如果需要更新，则筛选当前日期的数据更新
                    if(isUpdate){
                        String writeDateString = itemNode.get("write_date").asText().split(" ")[0];
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                        LocalDate writeDate = LocalDate.parse(writeDateString, formatter);
                        LocalDate currentDate = LocalDate.now();
                        // 比较当前日期和write_date
                        if (!writeDate.isEqual(currentDate)) {
                            continue;
                        }
                    }
                    propertyPolicy.setId(IdUtil.simpleUUID());
                    int flag = 0;
                    if (ObjectUtil.isNotNull(itemNode.get("id"))) {
                        propertyPolicy.setPolicyId(itemNode.get("id").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("write_date"))) {
                        propertyPolicy.setWriteDate(itemNode.get("write_date").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("word_code"))) {
                        String word_code = itemNode.get("word_code").asText();
                        if(word_code.length() > 255){
                            flag = 1;
                            propertyPolicy.setWordCode("此字段超长");
                        }else{
                            propertyPolicy.setWordCode(word_code);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("declare"))) {
                        String declare = itemNode.get("declare").asText();
                        if(declare.length() > 255){
                            flag = 1;
                            propertyPolicy.setDeclared("此字段超长");
                        }else{
                            propertyPolicy.setDeclared(declare);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("trend"))) {
                        String trend = itemNode.get("trend").asText();
                        if(trend.length() > 255){
                            flag = 1;
                            propertyPolicy.setTrend("此字段超长");
                        }else {
                            propertyPolicy.setTrend(trend);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("createUserName"))) {
                        propertyPolicy.setCreateUserName(itemNode.get("createUserName").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("source"))) {
                        String source = itemNode.get("source").asText();
                        if(source.length() > 255){
                            flag = 1;
                            propertyPolicy.setSource("此字段超长");
                        }else {
                            propertyPolicy.setSource(source);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("declare_project"))) {
                        String declare_project = itemNode.get("declare_project").asText();
                        if(declare_project.length() > 65535){
                            flag = 1;
                            propertyPolicy.setDeclareProject("此字段超长");
                        }else {
                            propertyPolicy.setDeclareProject(declare_project);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("max_support_fund"))) {
                        String max_support_fund = itemNode.get("max_support_fund").asText();
                        if(max_support_fund.length() > 255){
                            flag = 1;
                            propertyPolicy.setMaxSupportFund("此字段超长");
                        }else {
                            propertyPolicy.setMaxSupportFund(max_support_fund);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("is_other_platform"))) {
                        propertyPolicy.setIsOtherPlatform(itemNode.get("is_other_platform").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("province"))) {
                        propertyPolicy.setProvince(itemNode.get("province").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("bid_content"))) {
                        String bid_content = itemNode.get("bid_content").asText();
                        if(bid_content.length() > 65535){
                            flag = 1;
                            propertyPolicy.setBidContent("此字段超长");
                        }else {
                            propertyPolicy.setBidContent(bid_content);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("create_date"))) {
                        propertyPolicy.setCreateDate(itemNode.get("create_date").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("keyword"))) {
                        String keyword = itemNode.get("keyword").asText();
                        if(keyword.length() > 255){
                            flag = 1;
                            propertyPolicy.setKeyword("此字段超长");
                        }else {
                            propertyPolicy.setKeyword(keyword);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("bid_condition"))) {
                        String bid_condition = itemNode.get("bid_condition").asText();
                        if(bid_condition.length() > 255){
                            flag = 1;
                            propertyPolicy.setBidCondition("此字段超长");
                        }else {
                            propertyPolicy.setBidCondition(bid_condition);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("declare_object"))) {
                        String declare_object = itemNode.get("declare_object").asText();
                        if(declare_object.length() > 65535){
                            flag = 1;
                            propertyPolicy.setDeclareObject("此字段超长");
                        }else {
                            propertyPolicy.setDeclareObject(declare_object);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("support_object_id"))) {
                        String support_object_id = itemNode.get("support_object_id").asText();
                        if(support_object_id.length() > 255){
                            flag = 1;
                            propertyPolicy.setSupportObjectId("此字段超长");
                        }else{
                            propertyPolicy.setSupportObjectId(support_object_id);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("active"))) {
                        propertyPolicy.setActive(itemNode.get("active").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("province_name"))) {
                        propertyPolicy.setProvinceName(itemNode.get("province_name").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("sequence"))) {
                        String sequence = itemNode.get("sequence").asText();
                        if(sequence.length() > 255){
                            flag = 1;
                            propertyPolicy.setSequenced("此字段超长");
                        }else {
                            propertyPolicy.setSequenced(sequence);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("types_name"))) {
                        String types_name = itemNode.get("types_name").asText();
                        if(types_name.length() > 255){
                            flag = 1;
                            propertyPolicy.setTypesName("此字段超长");
                        }else {
                            propertyPolicy.setTypesName(types_name);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("release_date"))) {
                        propertyPolicy.setReleaseDate(itemNode.get("release_date").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("support_objectName"))) {
                        String support_objectName = itemNode.get("support_objectName").asText();
                        if(support_objectName.length() > 255){
                            flag = 1;
                            propertyPolicy.setSupportObjectname("此字段超长");
                        }else {
                            propertyPolicy.setSupportObjectname(support_objectName);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("name"))) {
                        String name = itemNode.get("name").asText();
                        if(name.length() > 65535){
                            flag = 1;
                            propertyPolicy.setName("此字段超长");
                        }else {
                            propertyPolicy.setName(name);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("old_id"))) {
                        String old_id = itemNode.get("old_id").asText();
                        if(old_id.length() > 255){
                            flag = 1;
                            propertyPolicy.setOldId("此字段超长");
                        }else {
                            propertyPolicy.setOldId(old_id);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("support_object"))) {
                        String support_object = itemNode.get("support_object").asText();
                        if(support_object.length() > 65535){
                            flag = 1;
                            propertyPolicy.setSupportObject("此字段超长");
                        }else {
                            propertyPolicy.setSupportObject(support_object);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("declare_condition"))) {
                        String declare_condition = itemNode.get("declare_condition").asText();
                        if(declare_condition.length() > 65535){
                            flag = 1;
                            propertyPolicy.setDeclareCondition("此字段超长");
                        }else {
                            propertyPolicy.setDeclareCondition(declare_condition);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("declare_materials"))) {
                        String declare_materials = itemNode.get("declare_materials").asText();
                        if(declare_materials.length() > 65535){
                            flag = 1;
                            propertyPolicy.setDeclareMaterials("此字段超长");
                        }else {
                            propertyPolicy.setDeclareMaterials(declare_materials);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("end_date"))) {
                        propertyPolicy.setEndDate(itemNode.get("end_date").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("declare_contacts"))) {
                        String declare_contacts = itemNode.get("declare_contacts").asText();
                        if(declare_contacts.length() > 65535){
                            flag = 1;
                            propertyPolicy.setDeclareContacts("此字段超长");
                        }else {
                            propertyPolicy.setDeclareContacts(declare_contacts);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("is_nationwide"))) {
                        propertyPolicy.setIsNationwide(itemNode.get("is_nationwide").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("city"))) {
                        propertyPolicy.setCity(itemNode.get("city").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("declare_support"))) {
                        String declare_support = itemNode.get("declare_support").asText();
                        if(declare_support.length() > 65535){
                            flag = 1;
                            propertyPolicy.setDeclareSupport("此字段超长");
                        }else {
                            propertyPolicy.setDeclareSupport(declare_support);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("content"))) {
                        propertyPolicy.setContent(itemNode.get("content").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("city_name"))) {
                        propertyPolicy.setCityName(itemNode.get("city_name").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("unpublished_support_fund"))) {
                        propertyPolicy.setUnpublishedSupportFund(itemNode.get("unpublished_support_fund").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("popularity"))) {
                        propertyPolicy.setPopularity(itemNode.get("popularity").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("department"))) {
                        propertyPolicy.setDepartment(itemNode.get("department").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("unscramble"))) {
                        String unscramble = itemNode.get("unscramble").asText();
                        if(unscramble.length() > 255){
                            flag = 1;
                            propertyPolicy.setUnscramble("此字段超长");
                        }else {
                            propertyPolicy.setUnscramble(unscramble);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("start_date"))) {
                        propertyPolicy.setStartDate(itemNode.get("start_date").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("is_processed"))) {
                        propertyPolicy.setIsProcessed(itemNode.get("is_processed").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("types"))) {
                        String types = itemNode.get("types").asText();
                        if(types.length() > 65535){
                            flag = 1;
                            propertyPolicy.setTypes("此字段超长");
                        }else {
                            propertyPolicy.setTypes(types);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("other_tag"))) {
                        String other_tag = itemNode.get("other_tag").asText();
                        if(other_tag.length() > 255){
                            flag = 1;
                            propertyPolicy.setOtherTag("此字段超长");
                        }else {
                            propertyPolicy.setOtherTag(other_tag);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("writeUser"))) {
                        String write_user = itemNode.get("writeUser").asText();
                        if(write_user.length() > 255){
                            flag = 1;
                            propertyPolicy.setWriteUser("此字段超长");
                        }else {
                            propertyPolicy.setWriteUser(write_user);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("department_name"))) {
                        propertyPolicy.setDepartmentName(itemNode.get("department_name").asText());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("types_code"))) {
                        String types_code = itemNode.get("types_code").asText();
                        if(types_code.length() > 255){
                            flag = 1;
                            propertyPolicy.setTypesCode("此字段超长");
                        }else {
                            propertyPolicy.setTypesCode(types_code);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("download_count"))) {
                        propertyPolicy.setDownloadCount(itemNode.get("download_count").asInt());
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("min_support_fund"))) {
                        String min_support_fund = itemNode.get("min_support_fund").asText();
                        if(min_support_fund.length() > 255){
                            flag = 1;
                            propertyPolicy.setMinSupportFund("此字段超长");
                        }else {
                            propertyPolicy.setMinSupportFund(min_support_fund);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("writeUserName"))) {
                        String write_user_name = itemNode.get("writeUserName").asText();
                        if(write_user_name.length() > 255){
                            flag = 1;
                            propertyPolicy.setWriteUserName("此字段超长");
                        }else {
                            propertyPolicy.setWriteUserName(write_user_name);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("createUser"))) {
                        String create_user = itemNode.get("createUser").asText();
                        if(create_user.length() > 255){
                            flag = 1;
                            propertyPolicy.setCreateUser("此字段超长");
                        }else {
                            propertyPolicy.setCreateUser(create_user);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("trend_name"))) {
                        String trend_name = itemNode.get("trend_name").asText();
                        if(trend_name.length() > 255){
                            flag = 1;
                            propertyPolicy.setTrendName("此字段超长");
                        }else {
                            propertyPolicy.setTrendName(trend_name);
                        }
                    }
                    if(ObjectUtil.isNotNull(itemNode.get("support_object_name").asText())){
                        String support_object_name = itemNode.get("support_object_name").asText();
                        if(support_object_name.length() > 255){
                            flag = 1;
                            propertyPolicy.setSupportName("此字段超长");
                        }else {
                            propertyPolicy.setSupportName(support_object_name);
                        }
                    }
                    if (ObjectUtil.isNotNull(itemNode.get("is_subscribe").asText())) {
                        propertyPolicy.setIsSubscribe(itemNode.get("is_subscribe").asText());
                    }
                    propertyPolicy.setPolicySource("园区无忧");
                    propertyPolicy.setPublishingStatus(1);
                    propertyPolicy.setRevocationStatus(1);
                    propertyPolicy.setPinnedStatus(0);

                    if(flag == 1){
                        baseMapper.insertPropertyPolicyFields(propertyPolicy);
                    }else {
                        baseMapper.insert(propertyPolicy);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String getYqPolicy(Integer pageNo,Integer pageSize){
        String loginKey = "pageSize" + pageSize + "&pageNo=" + pageNo +
                "&is_nationwide=&keyword=&typesCode=PolicyTypeProject&department=" +
                "&province=&city=&name=&content=&word_code=&support_object=&min_suppor" +
                "t_fund=&max_support_fund=&start_release_date=&end_release_date=&year=&status=&sort=SortTimeDESC&active=true";

        String requestUrl = "http://hzw.sctcc.cn/search/policy/ESPolicyController/getESPolicys";
        try{
            URL obj = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json, text/plain, */*");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Referer", "http://www.1751.org.cn/");
            conn.setRequestProperty("Origin", "http://www.1751.org.cn");
//            conn.setRequestProperty("Token", "75d6d935-ec86-4464-b787-af6e1b648e76");

            // 启用输出流
            conn.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.write(loginKey.getBytes(StandardCharsets.UTF_8));
            wr.flush();
            wr.close();

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            return response.toString();
        }catch (Exception e){
            e.getMessage();
        }
        return "读取失败";
    }

    public String getYgPolicy(Integer pageNo,Integer pageSize){
        String requestUrl = "https://cf.medv.com.cn/api/policy/seachpolicy?keyword=&page="+pageNo+"&limit="+
                pageSize+"&type=&dep_time=&province_id=0&city_id=&area_id=&open=1&user_id=77933";

        try{
            URL obj = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json, text/plain, */*");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 启用输出流
            conn.setDoOutput(true);
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            return unicodeDecode(response.toString());
        }catch (Exception e){
            e.getMessage();
        }
        return "读取失败";
    }

    public String getGdPolicy(Integer pageNo,Integer pageSize){
        String requestUrl = "https://cf.medv.com.cn/api/policy/seachpolicy?keyword=&page=" + pageNo + "&limit=" + pageSize +
                "&type=&dep_time=&province_id=0&city_id=&area_id=&open=&user_id=77933";

        try{
            URL obj = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json, text/plain, */*");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 启用输出流
            conn.setDoOutput(true);
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            return unicodeDecode(response.toString());
        }catch (Exception e){
            e.getMessage();
        }
        return "读取失败";
    }

    public String getPolicyDetail(String id){
        String apiUrl = "https://cf.medv.com.cn/api/policy/policyinfo?id="+id+"&user_id=77933";

        try {
            // 创建URL对象
            URL url = new URL(apiUrl);

            // 创建HttpURLConnection对象，并设置请求方法为GET
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json;charset=UTF-8");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 获取响应状态码
            int responseCode = connection.getResponseCode();

            // 若响应成功，则读取响应数据
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder responseData = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    responseData.append(line);
                }

                reader.close();

                return unicodeDecode(responseData.toString());
            } else {
                System.out.println("请求失败，响应码：" + responseCode);
            }
            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "读取失败";
    }

    /**
     * @Title: unicodeDecode
     * @Description: unicode解码
     */
    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

}
